<?php


namespace app\api\controller;


use app\BaseController;

//引入模型
use app\common\service\TenImService;
use app\models\user\Users;
use app\models\user\UserToken;

//处理redis

use app\Request;
use broadcast\services\UtilService as Util;
use think\exception\ValidateException;
use app\models\system\Appeal;

use app\models\system\Prohibit;
use broadcast\redis\setRedis;
use broadcast\services\CacheService;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;


//短信
/**
 * Class Index
 * @package app\api\controller
 */
class AuthController extends BaseController
{

    /**
     * 发送验证码
     */
    public function verify(Request $request) 
    {
        list($phone) = Util::postMore([['phone',0]],$request, true);
        session('website', $request->website());
        try {
            if(preg_match("/^1[345678]{1}\d{9}$/",$phone)) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        
        $Banlean = new Prohibit();
        $ip = getIps();
        //判断是否为被封禁用户或IP   start
        if ($ip != '') {
            $Banlean = $Banlean->where("ip",$ip);
        }
        $Banlean = $Banlean->find();
        
        if ($Banlean) return app("json")->fail("用户名或IP受限！");
        //判断是否为被封禁用户或IP   end



        //过期时间
        $time = 60*10;
        if(CacheService::get(session("website").'code_'.$phone))
            return app('json')->fail($time.'秒内有效');
        //随机验证码
        $code = rand(100000,999999);


         //腾讯
         $cred = new Credential("AKIDiDScYM48gyzjGXcLzmJbcLHxLSJxvhp9", "KQHG1ZrvkJceXGVqIXYM0PksvkkU4OaZ");//API密钥管理
         $httpProfile = new HttpProfile();
         $httpProfile->setEndpoint("sms.tencentcloudapi.com");//网址
 
         $clientProfile = new ClientProfile();//签名算法
         $clientProfile->setHttpProfile($httpProfile);//设置http相关参数
         $client = new SmsClient($cred, "", $clientProfile);
         $req = new SendSmsRequest();

         //请求参数
        $params = '{
        "PhoneNumberSet":["+86'.$phone.'"],
        "TemplateID":"647716",
        "Sign":"万名",
        "TemplateParamSet":["'.$code.'"],
        "SmsSdkAppid":"1400390364"}';
        $req->fromJsonString($params);

        $resp = $client->SendSms($req);
        $sad=json_decode(json_encode($resp), true);
        if ($sad["SendStatusSet"][0]['Code'] == 'Ok') {
            CacheService::set(session("website").'code_'.$phone, $code, $time);
            return app('json')->success('发送成功');
        }else{
            return app('json')->success('发送失败');
        }
    }

    /**
     * 发送验证码&&验证手机号是否存在
     */
    public function phoneVerify(Request $request) 
    {
        list($phone) = Util::postMore([['phone',0]],$request, true);
        session('website', $request->website());
        try {
            if (preg_match("/^1[345678]{1}\d{9}$/",$phone)) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        $isUsers = Users::where("phone",$phone)->find();
        if (empty($isUsers)) return app("json")->fail("该手机号不未绑定用户");

        //过期时间
        $time = 60*10;
        if (CacheService::get(session("website").'code_'.$phone))
            return app('json')->fail($time.'秒内有效');
        //随机验证码
        $code = rand(100000,999999);


         //腾讯
         $cred = new Credential("AKIDiDScYM48gyzjGXcLzmJbcLHxLSJxvhp9", "KQHG1ZrvkJceXGVqIXYM0PksvkkU4OaZ");//API密钥管理
         $httpProfile = new HttpProfile();
         $httpProfile->setEndpoint("sms.tencentcloudapi.com");//网址
 
         $clientProfile = new ClientProfile();//签名算法
         $clientProfile->setHttpProfile($httpProfile);//设置http相关参数
         $client = new SmsClient($cred, "", $clientProfile);
         $req = new SendSmsRequest();

         //请求参数
        $params = '{
        "PhoneNumberSet":["+86'.$phone.'"],
        "TemplateID":"647716",
        "Sign":"万名",
        "TemplateParamSet":["'.$code.'"],
        "SmsSdkAppid":"1400390364"}';
        $req->fromJsonString($params);

        $resp = $client->SendSms($req);
        $sad=json_decode(json_encode($resp), true);
        if ($sad["SendStatusSet"][0]['Code'] == 'Ok') {
            CacheService::set(session("website").'code_'.$phone, $code, $time);
            return app('json')->success('发送成功');
        }else{
            return app('json')->success('发送失败');
        }
    }


    /**
     * 验证手机号
     */
    public function verification(Request $request) 
    {
        session('website', $request->website());
        list($phone,$code) = Util::postMore([['phone',0],['code','']],$request, true);
        if ($phone == '') return app("json")->fail("手机号不存在");
        //验证手机号
        try {
            if (preg_match("/^1[345678]{1}\d{9}$/",$phone)) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        //验证验证码
        $verifyCode = CacheService::get(session("website").'code_'.$phone);
        if(!$verifyCode)
            return app('json')->fail('请先获取验证码');
        $verifyCode = substr($verifyCode, 0, 6);
        if($verifyCode != $code)
            return app('json')->fail('验证码错误');

        return  app("json")->success("手机号验证成功");

    }


   
    /**
     * 注册
     */
    public function register (Request $request) 
    {
        $data = Util::postMore([
            ['phone', ''],
            ['code', ''],
            ['username',""],
            ['nickname',''],
            ['password',''],
            ['repeat',''],
            ['roomid',""],
            ['extension','']
        ]);
        session('website', $request->website());
        if ($data['phone'] == '') return app("json")->fail("手机号不存在");
        //验证手机号
        try {
            if (preg_match("/^1[345678]{1}\d{9}$/",$data['phone'])) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        //验证验证码
        $verifyCode = CacheService::get(session("website").'code_'.$data['phone']);
        if(!$verifyCode)
            return app('json')->fail('请先获取验证码');
        $verifyCode = substr($verifyCode, 0, 6);
        if($verifyCode != $data['code'])
            return app('json')->fail('验证码错误');
        if ($data['username'] == '') return app("json")->fail("用户名不能为空");
        if ($data['nickname'] == '') return app("json")->fail("昵称不能为空");
        if ($data['password'] == "") return app("json")->fail("密码不能为空");
        if ($data['repeat'] == '') return app("json")->fail("请再次输入密码");
        if ($data['password'] != $data['repeat']) return app("json")->fail("两次输入密码不一致");
        //判断用户名是否存在
        $info = Users::where("username",$data['username'])->whereOr("phone",$data['phone'])->find();
        
        if ($info) {
            return app("json")->fail("用户已经存在");
        }else {
            $ip = getIps();
            $user = [
                'rooms' => $data['roomid'],
                'create_time' => time(),
                'lately_time' => time(),
                'password' => md5($data['password']),
                'username' => $data['username'],
                'nickname' => $data['nickname'],
                'online'   => 1,
                'create_ip' => setIp($ip),            
                'create_home' => ascriptions($ip),
                "phone" => $data['phone'],
                'group' => 3
            ];
            if ($data['extension'] != '') $user['extension'] = $data['extension'];
            $model = new Users();
            $save = $model->save($user);
            if ($save) {
                $users =  Users::where("id",$model->id)->find()->toArray();
                setRedis::setCache(session("website"),'usersList#'.$model->id.":".$users['username'],$users,0);
                setRedis::addRegisterCount(session("website"),date('Y-m-d'),$data['roomid']);

                //处理数据
                $time = strtotime("+ 500hour");
                $token = UserToken::tokenCreate($users['id'], $time);
                $users['sex'] = $users['sex'] == 1 ?  '男' : '女';
                 // 获取IM配置
                $imSettings = TenImService::getSettings($data['roomid'], $users);

                //处理多余数据
                unset($users['id']);
                unset($users['password']);
                unset($users['create_time']);
                unset($users['create_ip']);
                unset($users['lately_time']);
                unset($users['create_home']);
                unset($users['openid']);
                unset($users['realname']);
                unset($users['website']);
                unset($users['status']);
                unset($users['update_time']);
                unset($users['extension']);
                unset($users['online']);

                return app("json")->success('登录成功', ['token' => $token, 'expires_time' => $time, 'userInfo' => $users, 'imSettings' => $imSettings]);
            } else {
                return app("json")->fail("注册失败");
            }

        }
    }


    /**
     * 忘记密码
     */
    public function userForget (Request $request)
    {
        $data = Util::postMore([
            ['phone',''],
            ['password', ''],
        ]);

        session('website', $request->website());

        if ($data['phone'] == '') return app("json")->fail("手机号不存在");
        //验证手机号
        try {
            if (preg_match("/^1[345678]{1}\d{9}$/",$data['phone'])) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }
        $userModel = new Users();
        $info = $userModel->where("phone",$data['phone'])->find();
        if (empty($info)) return app("json")->fail("用户不存在");
        $userModel->password = md5($data['password']);
        $userModel->save();
        setRedis::setCache(session("website"),"usersList#".$info['id'].":".$info['username'],$info->toArray(),0);
        return app("json")->success("重新修改密码");
    }


    //提交申诉
    public function addAppeal(Request $request) 
    {
        $data = Util::postMore([
            ['username', ''],
            ['ip', ''],
            ['realname', ''],
            ['phone', ''],
            ['live_room', ''],
            ['content', ''],
            ['images', ''],
            ['code',''],
        ]);
        
        session('website', $request->website());
        if ($data['phone'] != '') {
            //验证手机号
            try {
                if (preg_match("/^1[345678]{1}\d{9}$/",$data['phone'])) {
                }else{
                    return app('json')->fail("手机号格式错误");
                }
            } catch (ValidateException $e) {
                return app('json')->fail($e->getError());
            }
            //验证验证码
            $verifyCode = CacheService::get(session("website").'code_'.$data['phone']);
            if(!$verifyCode)
                return app('json')->fail('请先获取验证码');
            $verifyCode = substr($verifyCode, 0, 6);
            if($verifyCode != $data['code'])
                return app('json')->fail('验证码错误');
            unset($data['code']);
        }
        
        
        $data['create_time'] = time();
        $data['website'] = $request->website();
        
        $appeal = new Appeal();
        $save = $appeal->save($data);
        return $save ? app('json')->success("提交成功") : app('json')->fail("提交失败");
    }
}